package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApFollowBehaviorServiceimpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Resource
    ApBehaviorEntryService apBehaviorEntryService;

    @Resource
    ApFollowBehaviorService apFollowBehaviorService;

    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null || dto.getFollowId() == null || dto.getUserId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询行为实体是否存在
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (apBehaviorEntry == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApFollowBehavior followBehavior = apFollowBehaviorService.getOne(Wrappers.<ApFollowBehavior>lambdaQuery().eq(ApFollowBehavior::getEntryId, apBehaviorEntry.getId()));

        if (followBehavior == null) {
            //保存用户行为
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setCreatedTime(new Date());
            apFollowBehavior.setEntryId(apBehaviorEntry.getId());
            apFollowBehavior.setFollowId(dto.getFollowId());
            apFollowBehaviorService.save(apFollowBehavior);
        }

        return ResponseResult.okResult();
    }
}
